package ca.psquared.superbrixgame.scheduler;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;

public abstract class IntervalTask implements ITask {

    private int interval = 0;
    private int intervalTimer = 0;
    private int delay = 0;
    private int delayTimer = 0;
    private int expiry = -1;
    private int expiryTimer = 0;

    public IntervalTask(int interval) {
        this.interval = interval;
        this.intervalTimer = interval;
    }

    public IntervalTask(int delay, int interval) {
        this(interval);
        this.delay = delay;
    }

    public IntervalTask(int delay, int interval, int expiry) {
        this(delay, interval);
        this.expiry = expiry;
    }

    @Override
    public final void execute(GameContainer gameContainer, int delta) throws SlickException {


        if (delayTimer >= delay) {

            if (intervalTimer >= interval) {
                intervalTimer = 0;
                onExecute(gameContainer, delta);
            }

            expiryTimer += delta;
            intervalTimer += delta;

        } else {
            delayTimer += delta;
        }

    }

    @Override
    public boolean isDone() {
        return expiry != -1 && expiryTimer > expiry;
    }

    protected abstract void onExecute(GameContainer gameContainer, int delta) throws SlickException;

    public void expireTimer() {
        intervalTimer = interval;
    }

    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }
}
